/*******************************************************************************
* Copyright (c) 2010, 2018 西安秦晔信息科技有限公司
* Licensed under the Apache License, Version 2.0 (the "License");
*    you may not use this file except in compliance with the License.
*    You may obtain a copy of the License at
*
*       http://www.apache.org/licenses/LICENSE-2.0
*
*    Unless required by applicable law or agreed to in writing, software
*    distributed under the License is distributed on an "AS IS" BASIS,
*    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*    See the License for the specific language governing permissions and
*    limitations under the License.
*******************************************************************************/
package com.qinyeit.webapp.controller.management.stores;

import com.alibaba.fastjson.JSONObject;
import com.qinyeit.serviceapp.entity.StoreInOrder;
import com.qinyeit.serviceapp.entity.StoreOutOrder;
import com.qinyeit.serviceapp.entity.enums.*;
import com.qinyeit.serviceapp.service.stores.StoreInOrderService;
import com.qinyeit.serviceapp.service.stores.StoreOutOrderService;
import com.qinyeit.serviceapp.service.stores.SupplierService;
import com.qinyeit.serviceapp.utils.SearchUtils;
import com.qinyeit.webapp.controller.management.BaseManagementController;
import com.qinyeit.webapp.utils.CurrentAccountUtils;
import com.qinyeit.webapp.utils.SearchableUtils;
import com.qinyetech.springstage.core.entity.search.Searchable;
import com.qinyetech.springstage.core.lang.QyMap;
import com.qinyetech.springstage.core.utils.JSONUtils;
import com.qinyetech.springstage.core.web.annotation.PageableDefaults;
import com.qinyetech.springstage.core.web.annotation.PermissionInfo;
import com.qinyetech.springstage.core.web.dto.ResponseResult;

import com.qinyeit.serviceapp.entity.ReceivePayment;
import com.qinyeit.serviceapp.service.stores.ReceivePaymentService;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * ClassName: ReceivePaymentsController <br/>
 * Function: receivePayment [供应商收付款单据] <br/>
 * date: 2019-03-05 10:06:09 <br/>
 *
 * @author liuwenjin
 * @version  1.0
 * @since JDK 1.8
 */
@RestController
@RequestMapping("/management/stores/receivePayments")
@PermissionInfo(parentName ="基础信息管理" ,parentOrder = 10,order = 10,code = "management_receivePayment:read",name ="供应商收付款单据",deleteAble = false)
public class ReceivePaymentsController extends BaseManagementController{

	@Autowired
	private ReceivePaymentService receivePaymentService;
	@Autowired
	private StoreInOrderService storeInOrderService;
    @Autowired
    private StoreOutOrderService storeOutOrderService;
    @Autowired
	private SupplierService supplierService;
    //TODO include的字段,支持jsonPath
	private final String [] keys = {"id","supplierId","supplierName","no","amount","giftAmount","type","operatorName","operatorTime","remark"};

    @RequiresPermissions("management_receivePayment:show")
    @PermissionInfo(code = "management_receivePayment:show",name ="查看",deleteAble = false)
    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST})
    @PageableDefaults(sort = "id=desc")//默认按照id降序
    public ResponseResult<JSONObject> index(Searchable searchable){
        Page<ReceivePayment> receivePaymentPage = receivePaymentService.findAll(searchable);
        return ok("查询成功", JSONUtils.include(receivePaymentPage, keys));
    }

    /**
     * 前台根据供应商 搜索 supplierName
     *  类型搜索：总部入库/总部出库\
     *  时间 ：in_time 入库 / outTime 出库
     * @param searchable
     * @param type 订单类型
     * @return
     */
    @GetMapping("/create")
    public ResponseResult<QyMap> _new(Searchable searchable, ReceivePaymentType type){
        QyMap map=QyMap.NEW();
        searchable = SearchableUtils.newSearchableWithMerchantFilter(searchable);
        searchable.addSearchParam("paymentState_eq", PaymentState.NORMAL);
        if(ReceivePaymentType.STOREIN == type){
            //查询入库单
            List<StoreInOrder> storeInOrders = storeInOrderService.findWithSort(searchable);
            map.setv("orders",JSONUtils.include(storeInOrders,new Class[]{StoreInType.class,StoreInState.class,PaymentState.class},"id","no","supplierId","warehouseId","inTime","type","amount","state","remark","createAt","warehouseName","supplierName","storeId","storeName","giftAmount","payAmount","paymentState"));
        }else if (ReceivePaymentType.STOREOUT == type){
            //查询出库单
           List<StoreOutOrder> storeOutOrders = storeOutOrderService.findWithSort(searchable);
           map.setv("orders",JSONUtils.include(storeOutOrders,new Class[]{StoreOutType.class, StoreOutState.class,PaymentState.class},"id","no","supplierId","warehouseId","outTime","type","amount","state","remark","supplierName","warehouseName","createAt","storeId","storeName","giftAmount","payAmount","paymentState"));
        }
        initFormDate(map);
        return ok("初始化成功", map);
    }

    /**
     * 保存收/付款单
     * @param data
     * @param bindingResult
     * @return
     */
    @RequiresPermissions("management_receivePayment:create")
    @PermissionInfo(code = "management_receivePayment:create",name ="新增",deleteAble = false)
    @PostMapping("/create")
    public ResponseResult<String> create(@RequestBody JSONObject data, BindingResult bindingResult){
        if (bindingResult.hasErrors()) {
            return super.validateFail(bindingResult);
        }
        receivePaymentService.saveData(data, CurrentAccountUtils.getAuthenticatedMerchantGroupID(),CurrentAccountUtils.getAuthenticatedEmployeeName());
        return ok("保存成功");
    }

    @GetMapping("/{id}")
    public ResponseResult<JSONObject> show(@ModelAttribute ReceivePayment receivePayment){
        return ok("查询成功", JSONUtils.include(receivePayment, keys));
    }

    @GetMapping("/{id}/update")
    public ResponseResult<QyMap> edit(@ModelAttribute ReceivePayment receivePayment){
        QyMap map=QyMap.NEW();
        map.setv("receivePayment",JSONUtils.include(receivePayment, keys));
        initFormDate(map); //TODO 如果没有需要初始化的数据，测则删除该行
        return ok("查询成功",map);
    }

    @RequiresPermissions("management_receivePayment:update")
    @PermissionInfo(code = "management_receivePayment:update",name ="修改",deleteAble = false)
    @PutMapping("/{id}/update")
    public ResponseResult<String> update(@ModelAttribute @Valid ReceivePayment receivePayment,BindingResult bindingResult){
//        if(receivePaymentService.exists(buildExists(null, "no", receivePayment.getNo()))){
//             bindingResult.rejectValue("no","no.error","编号已经存在");
//        }
        if (bindingResult.hasErrors()) {
            return super.validateFail(bindingResult);
        }
        receivePaymentService.update(receivePayment);
        return ok("更新成功", null);
    }

    @RequiresPermissions("management_receivePayment:destory")
    @PermissionInfo(code = "management_receivePayment:destory",name ="删除",deleteAble = false)
    @DeleteMapping("/{id}")
    public ResponseResult<String> destory(@PathVariable Long id){
        receivePaymentService.logicDelete(id);
        return ok("删除成功", null);
    }

    @ModelAttribute
    public void preparedData(@PathVariable(value="id",required = false) String id,Model model){
        if(StringUtils.isNotBlank(id)){ //如果路径中有id参数则查询实体对象
            ReceivePayment receivePayment = receivePaymentService.findById(Long.valueOf(id));
            model.addAttribute(receivePayment);
        }
    }

    /**
     * 初始化表单数据
     * @param qyMap
     */
    private void initFormDate(QyMap qyMap){
        //单据类型
        qyMap.setv("receivePaymentTypes",ReceivePaymentType.values());
        //供应商
        Searchable searchable = SearchableUtils.newSearchableWithMerchantFilter();
        qyMap.setv("suppliers",JSONUtils.include(supplierService.findWithSort(searchable),"id","no","name","fullName","balanceMode","linker","phone","address","state","bankName","bankNo","creditNo","spell"));
    }


}